import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

// 基础配置
const baseConfig: AxiosRequestConfig = {
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
};

// 创建不同服务的axios实例
const authInstance = axios.create({
  ...baseConfig,
  baseURL: '/api', // 通过vite代理到 http://172.27.2.110
});

const aiInstance = axios.create({
  ...baseConfig,
  baseURL: '/deepseek', // 通过vite代理到 https://openapi.youdao.com
});

const voiceInstance = axios.create({
  ...baseConfig,
  baseURL: '/asr', // 通过vite代理到 https://vop.baidu.com
});

const ttsInstance = axios.create({
  ...baseConfig,
  baseURL: '/tts', // 通过vite代理到 https://openapi.youdao.com
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'Accept': 'audio/mp3,application/json',
  },
});

// 通用请求拦截器
const setupInterceptors = (instance: AxiosInstance, serviceName: string) => {
  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      // 添加认证token
      const token = localStorage.getItem('token');
      if (token && serviceName === 'auth') {
        config.headers.Authorization = `Bearer ${token}`;
      }
      
      console.log(`[${serviceName}] 发送请求:`, {
        url: config.url,
        method: config.method,
        data: config.data,
      });
      
      return config;
    },
    (error) => {
      console.error(`[${serviceName}] 请求错误:`, error);
      return Promise.reject(error);
    }
  );

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      console.log(`[${serviceName}] 响应成功:`, {
        url: response.config.url,
        status: response.status,
        data: response.data,
      });
      return response;
    },
    (error) => {
      console.error(`[${serviceName}] 响应错误:`, {
        url: error.config?.url,
        status: error.response?.status,
        message: error.message,
        data: error.response?.data,
      });
      
      // 统一错误处理
      if (error.response?.status === 401) {
        // 未授权，清除token并跳转到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        localStorage.removeItem('userId');
        localStorage.removeItem('role');
        window.location.href = '/login';
      }
      
      return Promise.reject(error);
    }
  );
};

// 为每个实例设置拦截器
setupInterceptors(authInstance, 'auth');
setupInterceptors(aiInstance, 'ai');
setupInterceptors(voiceInstance, 'voice');
setupInterceptors(ttsInstance, 'tts');

export { authInstance, aiInstance, voiceInstance, ttsInstance };
export default authInstance;